//
//  DownloadListController.m
//  News
//
//  Created by lanou3g on 15/11/9.
//  Copyright © 2015年 songhaowen. All rights reserved.
//

#import "DownloadListController.h"
#import "UIView+Extension.h"
#import "DownloadCell.h"
#import "VideoModel.h"
#import "VideoDownLoadManager.h"
#import <MediaPlayer/MediaPlayer.h>
#import "MBProgressHUD+MJ.h"
#import "FMDB.h"

@interface DownloadListController () <VideoDownLoadManagerDelegate, DownloadCellDelegate>
{
    MPMoviePlayerViewController *_moviePlayVC;
}

@property (nonatomic, copy) NSString *videoSizeString;

@property (nonatomic, strong) UILabel *tipLabel;

@end

@implementation DownloadListController

SingletonM(DownloadListController)

static FMDatabase *_db;
+ (void)initialize
{
    // 1.打开数据库
    NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"news_shw.sqlite"];
    NSLog(@"---initialize---%@", path);
    _db = [FMDatabase databaseWithPath:path];
    [_db open];
    
    // 2.创表
    [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS shw_videoDownload (videoModel BLOB, videoPath TEXT, videoSize integer);"];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.title = @"下载列表";
    
    
    [self.navigationController.navigationBar setBackgroundColor:[UIColor orangeColor]];
    
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
    NSLog(@"%@", path);
    
    [VideoDownLoadManager sharedVideoDownLoadManager].delegate = self;
    // 注册新的下载通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(newMovieDidStatrtDownAction:) name:k_newVideoDidStartDown object:nil];
    //注册下载完成的通知
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(videoDidFinishedSuccess:) name:k_videoDidDownedFinishedSuccess object:nil];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
    // 将数据库中的数据加入到列表中一次
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        FMResultSet *set = [_db executeQuery:@"SELECT * FROM shw_videoDownload;"];
        
        // 不断往下取数据
        while (set.next) {
            // 获得当前所指向的数据
            NSData *data = [set dataForColumn:@"videoModel"];
            VideoModel *model = [NSKeyedUnarchiver unarchiveObjectWithData:data];
            model.videoPath = [set objectForColumnName:@"videoPath"];
            
            model.videoSize = [set doubleForColumn:@"videoSize"];
            model.isDownFinished = YES;
            [[VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray addObject:model];
        }
        [self.tableView reloadData];
    });
    
    
    
    // 设置提示label
    [self setUpTipView];
    // 判断是否有下载
    [self judgeHasTask];
    
    
}


#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    DownloadCell *cell = [DownloadCell cellWithTableView:tableView];
    
    VideoModel *model = [VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray[indexPath.row];
    cell.model = model;
    cell.delegate = self;
    
    // 如果已经下载完成, 则隐藏进度条
    if (model.isDownFinished) {
        cell.progressView.hidden = YES;
        cell.totalProgressView.hidden = YES;
        cell.playButton.hidden = YES;
        cell.speedLabel.hidden = YES;
        cell.videoSizeLabel.text = self.videoSizeString;
    } else {
        cell.playButton.selected = YES;
    }
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 80;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel *model = [VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray[indexPath.row];
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [[VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray removeObjectAtIndex:indexPath.row];
        
        // UI删除
        [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
        
        // 删除保存的url
        NSArray *keyArr = [[VideoDownLoadManager sharedVideoDownLoadManager].httpOperationDict allKeys];
        for (NSString *urlString in keyArr) {
            if ([urlString isEqualToString:model.mp4_url]) {
                [[VideoDownLoadManager sharedVideoDownLoadManager].httpOperationDict removeObjectForKey:urlString];
                return;
            }
        }
        // 删除目录下的文件
        NSError *error = nil;
        [[NSFileManager defaultManager] removeItemAtPath:model.videoPath error:&error];
        
        // 删除数据库中的model
        BOOL deleteResult = [_db executeUpdateWithFormat:@"delete from shw_videoDownload where videoPath = %@",model.videoPath];
        NSLog(@"--deleteResult--%d", deleteResult);
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    VideoModel *model = [VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray[indexPath.row];
    // 下载完才可以播放
    if (!model.isDownFinished) {
        [MBProgressHUD showError:@"未完成下载"];
        return;
    }
    NSLog(@"---path----%@", model.videoPath);
    NSURL *url = [NSURL fileURLWithPath:model.videoPath];
    _moviePlayVC = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
    
    // 模态推出播放视频的控制器
    [self presentMoviePlayerViewControllerAnimated:_moviePlayVC];
    
    _moviePlayVC.moviePlayer.movieSourceType = MPMovieSourceTypeFile;
    [_moviePlayVC.moviePlayer play];
}


#pragma mark - VideoDownLoadManagerDelegate
- (void)videoDidUpdatedProgressWithVideoModel:(VideoModel *)model
{
    NSMutableArray *isContainArr = [VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray;
    if (![isContainArr containsObject:model]) return;
    
    NSUInteger index = [isContainArr indexOfObject:model];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    DownloadCell *cell = (DownloadCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    
    // 判断当前 cell 是否正在显示
    if ([[self.tableView visibleCells] containsObject:cell]) {
        cell.videoProgress = model.videoProgress;
    }
}

- (void)videoDidUpdatedDownloadSpeedWithVideoModel:(VideoModel *)model speed:(CGFloat)speed
{
    NSMutableArray *isContainArr = [VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray;
    if (![isContainArr containsObject:model]) return;
    
    NSUInteger index = [isContainArr indexOfObject:model];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    DownloadCell *cell = (DownloadCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    
    // 判断当前 cell 是否正在显示
    if ([[self.tableView visibleCells] containsObject:cell]) {
        cell.speed = speed;
    }
}

#pragma mark - DownloadCellDelegate
- (void)downloadCellPlayButtonClicked:(DownloadCell *)cell isPlay:(BOOL)isPlay
{
    NSUInteger index = [self.tableView indexPathForCell:cell].row;
    VideoModel *model = [VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray[index];
    if (isPlay) {
        [[VideoDownLoadManager sharedVideoDownLoadManager] downloadResumeWithModel:model];
    } else {
        [[VideoDownLoadManager sharedVideoDownLoadManager] downloadPausewithModel:model];
    }
}

#pragma mark - 通知
- (void)newMovieDidStatrtDownAction:(NSNotification *)sender
{
    // 1. 刷新表格
    [self.tableView reloadData];
    
    // 2. 设置播放按钮为下载状态
    VideoModel *videoModel = sender.object;
    NSInteger index = [[VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray indexOfObject:videoModel];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    DownloadCell *cell = (DownloadCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    
    cell.playButton.selected = YES;
}

- (void)videoDidFinishedSuccess:(NSNotification *)sender
{
    VideoModel *videoModel = sender.object;
    NSInteger index = [[VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray indexOfObject:videoModel];
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:index inSection:0];
    DownloadCell *cell = (DownloadCell *)[self.tableView cellForRowAtIndexPath:indexPath];
    // 设置 cell 上的下载按钮为完成状态
    cell.playButton.selected = NO;
    cell.progressView.hidden = YES;
    cell.totalProgressView.hidden = YES;
    cell.playButton.hidden = YES;
    cell.speedLabel.hidden = YES;
    
    // 赋值文件大小
    NSString *videoSizeString = [NSString string];
    if (videoModel.videoSize < 1024) {
        videoSizeString = [NSString stringWithFormat:@"%.02fB", videoModel.videoSize];
    } else if (videoModel.videoSize < 1024 * 1024 && videoModel.videoSize > 1024) {
        videoSizeString = [NSString stringWithFormat:@"%.02fKB", videoModel.videoSize / 1024];
    } else {
        videoSizeString = [NSString stringWithFormat:@"%.02fM", videoModel.videoSize / (1024 * 1024)];
    }
    self.videoSizeString = videoSizeString;
    cell.videoSizeLabel.text = videoSizeString;
    
    // 将model存入数据库, 下次已进入就将下载好的视频导入
    NSData *modelData = [NSKeyedArchiver archivedDataWithRootObject:videoModel];
    [_db executeUpdateWithFormat:@"INSERT INTO shw_videoDownload(videoModel, videoPath, videoSize) VALUES (%@, %@ ,%f);", modelData, videoModel.videoPath, videoModel.videoSize];
    
}

#pragma mark - private Method
- (void)judgeHasTask
{
    if ([VideoDownLoadManager sharedVideoDownLoadManager].downVideoArray.count == 0) {
        self.tipLabel.hidden = NO;
    } else {
        self.tipLabel.hidden = YES;
    }
}

- (void)setUpTipView
{
    self.tipLabel.frame = CGRectMake(0, 0, self.view.width, 60);
    self.tipLabel.backgroundColor = [UIColor orangeColor];
    self.tipLabel.layer.cornerRadius = 10;
    self.tipLabel.layer.masksToBounds = YES;
    self.tipLabel.text = @"暂无下载项";
    self.tipLabel.textAlignment = NSTextAlignmentCenter;
}

#pragma mark - 懒加载
- (NSMutableArray *)taskArray
{
    if (_taskArray == nil) {
        _taskArray = [NSMutableArray array];
    }
    return _taskArray;
}



- (UILabel *)tipLabel
{
    if (_tipLabel == nil) {
        _tipLabel = [[UILabel alloc] init];
        [self.tableView addSubview:_tipLabel];
    }
    return _tipLabel;
}





@end
